<?php

class jqueryvalidateJs extends JsPlugin{
    
    private $validation = array();
    private $val_message = array();
    private $formquene = array();
    private $masks   = "";
    private $output  = "";
    private $formname = "";
    
    public function init() {
        $this->LoadResource("html", "Html");
        $this->LoadJsPlugin('jqueryui/blockui', 'bui');
        $this->Html->LoadJs("$this->url/js/maskedin");
        $this->Html->LoadJs("$this->url/js/jquery.validate.min");
    }
    
    static private $instance;
    public static function getInstanceOf($plugin){
        $class_name = __CLASS__;
        if (!isset(self::$instance)) {
            self::$instance = new $class_name($plugin);
        }

        return self::$instance;
    }

    public function setformname($formname){
        if($this->formname != ""){$this->formquene[] = $this->formname;}
        $this->formname         = $formname;
        $this->masks[$formname] = "";
    }
    
    public function addValidation($field, $validation, $message){
        if($this->validation != ""){
            $validation  = $validation;
        }
        if($this->val_message != ""){
            $message  = $message;
        }
        $this->validation [$this->formname][$field][]  = $validation;
        $this->val_message[$this->formname][$field][]  = $message;
    }
    
    public function addMask($mask){
        $this->masks[$this->formname] .= $mask . " \n\n\t ";
    }
    
    public function validate($form, $ajax){
        $esp = (DEBUG)?"\n\t\t":"";
        $tab = (DEBUG)?"\t":"";
        
        $vig = "$esp$tab";
        $this->output .= $this->masks[$this->formname]." $('#$form').validate({ $esp$esp rules:{";
        foreach($this->validation[$this->formname] as $field => $rules){
            $rule = implode(", ", $rules);
            $this->output .= "$vig \"$field\":{ $rule }";
            $vig = ", $esp$tab";
        }
        $vig = "";
        $this->output .= " $esp} , $esp$esp messages:{";
        foreach($this->val_message[$this->formname] as $field => $messages){
            $msg           = implode(", ", $messages);
            $this->output .= "$vig \"$field\":{ $msg }";
            $vig = ", $esp$tab";
        }
        $caract = ($ajax)?",":"";
        $this->output .= "$esp},$esp
            success: function(label) {
                $('#v'+label.attr('for')).text('Ok!').removeClass('erro').addClass('valid_msg');
            },$esp
            errorPlacement: function(label, element) {
                $('#v'+label.attr('for')).text(label.text()).removeClass('valid_msg').addClass('erro'); 
            }$caract";
        
        $addAjax = "";
        if($ajax){
            $this->output .= "
            submitHandler: function(form) {
                $.ajax({
                    url: $('#'+form.id).attr('action'),
                    type: 'POST',
                    data: $('#'+form.id).serialize(),
                    dataType: 'json',
                    beforeSend: function(){
                        blockUI_wait(\"Enviando dados...\");
                        $('#erro').hide();
                        $('#success').hide();
                        $('.erro').delay('1200').fadeOut('slow');
                        $('.valid_msg').delay('1200').fadeOut('slow');
                    },
                    success: function(json) {
                        blockUI_unwait();
                        if(json.status == 1){
                            if(json.is_editing != 1) $('#$form')[0].reset();
                            if (typeof json.success != 'undefined') blockUI_success(json.success);
                            else if(typeof json.alert != 'undefined') blockUI_alert(json.alert);
                            else blockUI_error('Operação concluída, mas sem resposta do servidor!');
                        }else{
                            if (typeof json.erro != 'undefined') blockUI_error(json.erro);
                            else blockUI_error('Operação concluída, mas sem resposta do servidor!');
                            for (var camp in json){
                                 $('#v'+camp).text(json[camp]).fadeIn('slow').addClass('erro').removeClass('valid_msg');
                            }
                        }

                    },
                    error: function(erro){
                        blockUI_unwait();
                        blockUI_error(\"Erro na comunicação com o site\");
                    }

                });
            }";
            $addAjax = "$('<input type=\"hidden\" id=\"ajax\" name=\"ajax\" value=\"true\" />').appendTo('#$form');";
        }

        $this->output .= "}); $addAjax";
        $this->Html->LoadJQueryFunction($this->output);
        
        //reseta as variaveis
        unset($this->validation[$this->formname]);
        unset($this->val_message[$this->formname]);
        unset($this->masks[$this->formname]);
        $this->formname = array_pop($this->formquene);
        $this->output = "";
        echo "<style>.closemsg{color:white; font-size:12px; float:right; cursor: Pointer;}</style>";
    } 
}

?>